% if 2 parameters are specified, xmin = 0, and xmax is the maximum value
% that occurs in the data
% if 3 arguments are specified, the 3rd is assumed to be xmin
function [stats,rsquared] = fitlineonloglog(x,y,xmin,xmax)

% if no xmin is specified, set it to 0
if (nargin < 3)
    xmin = 0;
    xmax = max(x);
end

if (nargin < 4)
    xmax = max(x);
end

%eliminate zeros because taking the logarithm
y = y(x>0);
x = x(x>0);

x = x(y>0);
y = y(y>0);

%also ignore values outside min and max specified by call
xfit = x(x>=xmin);
yfit = y(x>=xmin);
xfit = xfit(xfit<=xmax);
yfit = yfit(xfit<=xmax);

y = log(yfit);
x = log(xfit);

stats = regstats(y,x,'linear','all');

% compute r-squared
yhat = stats.yhat;
RSS = sum((yhat-mean(y)).^2); % regression sum of squares
TSS = sum((y-mean(y)).^2); % total sum of squares
rsquared = RSS ./ TSS;